package com.magold.start.splash;

import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.entity.modifier.AlphaModifier;
import org.andengine.entity.scene.Scene;
import org.andengine.util.call.Callback;
import org.andengine.util.color.Color;

import com.magold.sprite.IMultiTextureSprite;

public class LightEvent implements ISplashEvent{
	private static final Color LIGHT_COLOR = new Color(1.0f,1.0f,210/255.0f);
	
	private final Scene mScene;
	private final IMultiTextureSprite mBulbSprite;

	private final Callback<Object> mCallback;
	private final boolean mIsLightOn;

	public LightEvent(boolean pIsLightOn, Scene pScene, IMultiTextureSprite pBulbSprite,
			Callback<Object> pCallback) {
		mIsLightOn = pIsLightOn;
		mScene = pScene;
		mBulbSprite = pBulbSprite;
		mCallback = pCallback;
	}

	@Override
	public void perform() {
		if (mIsLightOn) {
			lightOn();
		} else {
			lightOff();
		}
	}
	
	private void lightOn() {
		ColorModifier modifier = new ColorModifier(1.0f, Color.BLACK, LIGHT_COLOR, mCallback);
		mScene.registerUpdateHandler(modifier);
		mBulbSprite.setVisible(true);
		mBulbSprite.animate(IMultiTextureSprite.DEFAULT_REFRESH_GAP * 2);
	}
	
	private void lightOff() {
		ColorModifier colorModifier = new ColorModifier(1.0f, LIGHT_COLOR, Color.BLACK, null);
		mScene.registerUpdateHandler(colorModifier);
		AlphaModifier alphaModifier = new AlphaModifier(1.0f, 1.0f, 0.0f);
		mBulbSprite.registerEntityModifier(alphaModifier);
	}
	
	private class ColorModifier implements IUpdateHandler {
		private final float mDuration;
		private final Color mFrom;
		private final Color mTo;
		
		private float mSecondsElapsed;
		private final Callback<Object> mCallback;
		
		public ColorModifier(float pDuration, Color pFrom, Color pTo, Callback<Object> pCallback) {
			mDuration = pDuration;
			mFrom = pFrom;
			mTo = pTo;
			mCallback = pCallback;
		}
		
		@Override
		public void onUpdate(float pSecondsElapsed) {
			mSecondsElapsed += pSecondsElapsed;
			if (mSecondsElapsed > mDuration) {
				mScene.getBackground().setColor(mTo);
				mScene.unregisterUpdateHandler(this);
				if(mCallback != null) {
					mCallback.onCallback(null);
				}
				return;
			}
			
			float percent = mSecondsElapsed/mDuration;
			float red = (1-percent) * mFrom.getRed() + percent * mTo.getRed();
			float green = (1-percent) * mFrom.getGreen() + percent * mTo.getGreen();
			float blue = (1-percent) * mFrom.getBlue() + percent * mTo.getBlue();
			mScene.getBackground().setColor(red, green, blue);
		}

		@Override
		public void reset() {
		}
	}
}

